package org.NooLab.itexx.app.processes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;



import org.NooLab.utilities.files.DFutils;

import jlibs.core.lang.JavaProcessBuilder;



public class NlpProcessExt {

	ProcessAdmin processAdmin;
	JavaProcessBuilder jvm;
	
	int initialHeap;
	int maxHeap ;
	
	String jarFilename="" , mainClass="";
	String jarFilePath="", appWorkingDir="";
	String extLibPath="";

	private String[] arguments;

	
	
	
	// ========================================================================
	public NlpProcessExt( ProcessAdmin procAdmin, int index, String[] args) {
		processAdmin = procAdmin;
		arguments = args;
	}
	// ========================================================================
	
	public void startExternalLingServer() throws InterruptedException {
		
		
		String appsecret,name,homedir ;
		String ports,argumentStr;
		
		
		
		try {
			

			
			
			String path = processAdmin.appProperties.getOwnBinPath() ;
			path = DFutils.createPath(path, "bin/NooLabTikaServer.jar");
	
			argumentStr =  processAdmin.strgutil.arr2text(arguments, "", "  ") ;
			
			// TODO this is different on different platforms
			// mac osx folder action: Runtime.getRuntime().exec(new String[] { "open", instFolder.toString() })
			// we probably need the full path to java, which we get by System.property  java.home
			// windows TODO better use String[] instead of a string...
            Process extProcess ;
            
            
            // extProcess = Runtime.getRuntime().exec("cmd /c start  "+path+"  "+argumentStr);
            
            extProcess = Runtime.getRuntime().exec("cmd /c start javaw -jar "+path+"  "+argumentStr);
            
            
            
            
			StreamGobblerL errorGobbler = new StreamGobblerL(extProcess.getErrorStream(), "ERR  ");

			// any output?
			StreamGobblerL outputGobbler = new StreamGobblerL(extProcess.getInputStream(), "---");

			// kick them off
			errorGobbler.start();
			outputGobbler.start();
			
			int exitVal = extProcess.waitFor();
			System.out.println("ExitValue: " + exitVal);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
}





class StreamGobblerL extends Thread {
	InputStream is;
	String type;

	StreamGobblerL(InputStream is, String type) {
		this.is = is;
		this.type = type;
	}

	public void run() {
		
		try {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(type + "[x] " + line);
			}

		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}